﻿using AutoMapper;
using B.S.ProcessEgine.API.Applocations.Commands.FormInfoCommand;
using B.S.ProcessEgine.API.Dtos.RequestDto;
using B.S.ProcessEgine.Domain.Entities;
using B.S.ProcessEgine.ErrorCode;
using B.S.ProcessEgine.Infractructure.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.ProcessEgine.API.Applocations.CommandHandlers.FormInfohandler
{
    public class GetFormCommandHandler : IRequestHandler<GetFormCommand, ApiResult<IList<Domain.Entities.FormInfo>>>
    {
        private readonly IFormInfoRepository _formRepository;
        private readonly IFormTypeRepository _formTypeRepository;
        private readonly IMapper _mapper;

        public GetFormCommandHandler(IFormInfoRepository formRepository,  IMapper mapper, IFormTypeRepository formTypeRepository)
        {
            _formRepository = formRepository;
            _mapper = mapper;
            _formTypeRepository = formTypeRepository;
        }


        public async Task<ApiResult<IList<Domain.Entities.FormInfo>>> Handle(GetFormCommand request, CancellationToken cancellationToken)
        {
            var list = await _formRepository.GetAll().ToListAsync(cancellationToken);

            if (request.TypeId != 0)
            {
                list = list.Where(x => x.TypeId == request.TypeId).ToList();
            }

            var form = _mapper.Map<IList<Domain.Entities.FormInfo>>(list);

            return ApiResult<IList<Domain.Entities.FormInfo>>.Success(form,StateCodeEnum.Ok);
        }
    }
}
